package com.xiaoma.tpo.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.xiaoma.tpo.dao.*;
import com.xiaoma.tpo.domain.*;
import com.xiaoma.tpo.dto.*;
import com.xiaoma.tpo.utils.Encrypt;
import com.xiaoma.tpo.utils.Pager;
import com.xiaoma.tpo.utils.TPOUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserDao userDao;
    
    @Autowired
    private UserListeningDao listeningDao;

    @Autowired
    private UserAchievementDao achievementDao;

    @Autowired
    private UserFollowDao followDao;

    @Autowired
    private MessagesDao messagesDao;

    @Autowired
    private UserBdpushBindDao bindDao;

    
    @Autowired
    private UserFriendDao userFriendDao;
    
    @Autowired
    private UserListeningRecordingDao userListeningRecordingDao;
    @Autowired
    private TUserDao tUserDao;

    private static final Logger LOG = LoggerFactory.getLogger(UserService.class);
    public User findByNameAndPwd(String name, String password) {
        User entity = new User();
        entity.setName(name);
        entity.setPassword(password);
        List<User> users = userDao.findByColumns(entity);
        return users.size() > 0 ? users.get(0) : null;
    }
    
    public User findById(int id) {
        return userDao.getById(id);
    }
    
    public User findByName(String name) {
        User entity = new User();
        entity.setName(name);
        List<User> users = userDao.findByColumns(entity);
        return users.size() > 0 ? users.get(0) : null;
    }
    
    public boolean duplicated(int id, String name) {
        return userDao.duplicated(id, name);
    }
    
    public void updateVisitTime(User user) {
        user.setLastVisit(new Date());
        userDao.update(user);
    }
    
    
    public User findByToken(String token) {
        User entity = new User();
        entity.setToken(token);
        List<User> users = userDao.findByColumns(entity);
        return users.size() > 0 ? users.get(0) : null;
    }
    
    public int save(User user) {
        return userDao.insert(user);
    }
    
    public void update(User user) {
        userDao.update(user);
    }
    
    public int saveUserListening(UserListening userListening) {
        return listeningDao.insert(userListening);
    }
    
    public void updateUserListening(UserListening userListening) {
        listeningDao.update(userListening);
    }
    
    public UserListening findUserListeningByUserIdAndDate(int userId, String date) {
        UserListening entity = new UserListening();
        entity.setUserId(userId);
        entity.setDate(date);
        List<UserListening> listenings = listeningDao.findByColumns(entity);
        return listenings.size() > 0 ? listenings.get(0) : null;
    }
    
    public Map<String, String> getUserListeningRankingAndRateByDate(int listeningCount, String date) {
        Map<String, String> result = new HashMap<String, String>();
        List<UserListening> listenings = listeningDao.orderByListeningCount(date);
        int ranking = 1;
        for (UserListening item : listenings) {
            if (listeningCount >= item.getListeningCount()) {
                break;
            }
            ranking++;
        }
        result.put("ranking", ranking+"");
        String rating = "";
        if (ranking == 1) {
            rating = "100%";
        } else {
            int lowCount = 0;
            for (int i = listenings.size() - 1; i >= 0; i--) {
                if (listeningCount == listenings.get(i).getListeningCount()) {
                    break;
                }
                lowCount++;
            }
//            float rate = lowCount * 100/(float)listenings.size();
//            DecimalFormat df = new DecimalFormat("0.00");
            int rate = lowCount * 100 / listenings.size();
            rating = rate + "%";
        }
        result.put("rating", rating);
        return result;
    }
    
    public List<TopListeningVo> getListeningTops(String date) {
        List<TopListeningVo> vos = listeningDao.getTopListenings(date, 20);
        if (vos.size() > 0) {
            TopListeningVo preVo = vos.get(0);
            preVo.setRanking(1);
            int count = 1;
            for (TopListeningVo vo : vos) {
                if (vo.getListeningCount() == preVo.getListeningCount()) {
                    vo.setRanking(preVo.getRanking());
                } else {
                    vo.setRanking(count);
                }
                preVo = vo;
                count++;
            }
        }
        return vos;
    }
    
    public int getUserTotalListeningCount(int userId) {
        return listeningDao.getUserTotalListeningCount(userId);
    }


    /**
     * 获取用户成就
     * @param userid  用户ID
     * @return
     */
    public List<UserAchievementDto> getAchievementList(int userid){
        List<UserAchievementDto> rsList = new ArrayList<UserAchievementDto>();
        UserAchievement ua = new UserAchievement();
        ua.setUserId(userid);
        List<UserAchievement> list = achievementDao.findByColumns(ua);
        UserAchievementDto dto = null;
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        for(UserAchievement data : list){
            dto = new UserAchievementDto();
            dto.setAchievement(data.getAchievement());
            dto.setDateTime(sf.format(data.getDateTime()));
            rsList.add(dto);
        }
        return rsList;
    }

    /**
     * 保存成就
     * @param user   用户信息
     * @param achievementsDto  成就内容
     */
    public void addAchievement(User user,UserAchievementsDto achievementsDto){
        UserAchievement achievement = null;
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        List<User> userList = getMyFollow(user.getId());
        for(UserAchievementDto dto : achievementsDto.getAchievements()){
            achievement = new UserAchievement();
            achievement.setUserId(user.getId());
            achievement.setAchievement(dto.getAchievement());
            try {
                achievement.setDateTime(sf.parse(dto.getDateTime()));
                achievementDao.insert(achievement);
                sendMsgToFollowUsers(userList,user,dto);
            } catch (ParseException e) {
                e.printStackTrace();
                LOG.error(e.getMessage());
            }

        }

    }

    /**
     * 获得成就时消息提示给关注用户
     * @param followList
     * @param user
     * @param achievement
     */
    public void sendMsgToFollowUsers(List<User> followList,User user,UserAchievementDto achievement){
        Messages msg = null;
        String content = "用户："+user.getNickname()+"，于"+achievement.getDateTime()+" 获得成就:"+achievement.getAchievement();
        for(User u :followList){
            msg = new Messages();
            msg.setUserId(u.getId());
            msg.setStatus(1);  //阅读状态，1未读，2已读
            msg.setContent(content);
            msg.setDateTime(new Date());
            messagesDao.insert(msg);
        }
    }

    /**
     * 根据用户id获取消息
     * @param userid
     * @param page  分页
     * @param status  状态  0全部,1未读，2已读
     * @return
     */
    public List<MessagesDto> getMessageByUser(int userid,int page,int status){

        List<Messages> list = messagesDao.getMessages(userid,page,status);
        List<MessagesDto> rsList = new ArrayList<MessagesDto>();
        MessagesDto dto = null;
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        for(Messages data : list){
            dto = new MessagesDto();
            dto.setId(data.getId());
            dto.setContent(data.getContent());
            dto.setDateTime(sf.format(data.getDateTime()));
            dto.setStatus(data.getStatus());
            rsList.add(dto);
        }
        return rsList;
    }

    /**
     * 消息标记为已读
     * @param msgId
     */
    public void updateStatus(int msgId){
        messagesDao.updateStatus(msgId);
    }
    /**
     * 添加关注
     * @param uf 关注对象
     * @return
     */
    public boolean addFollow(UserFollow uf){
        try {
            followDao.insert(uf);
        }catch (Exception e){
            LOG.error(e.getMessage());
            return false;
        }
        return true;
    }


    /**
     * 移除关注
     * @param uf  关注对象
     * @return
     */
    public boolean removeFollow(UserFollow uf){
        try {
            followDao.removeFollow(uf.getUserId(), uf.getFollowUserId());
        }catch (Exception ex){
            LOG.error(ex.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 检查是否关注过
     * @param uf
     * @return
     */
    public boolean checkFollow(UserFollow uf){
        List<UserFollow> list = followDao.findByColumns(uf);
        return list.size()>0?true:false;
    }

    /**
     * 获取我的关注列表
     * @param userid  用户ID
     * @return
     */
    public List<User> getMyFollow(int userid){
        List<User> rsList = new ArrayList<User>();
        List<User> list = followDao.getMyFollows(userid);
        User user = null;
        for(User data : list){
            user = new User();
            user.setId(data.getId());
            user.setName(data.getName());
            user.setNickname(data.getNickname());
            rsList.add(user);
        }
        return rsList;
    }


    /**
     * 用户绑定百度云推送数据
     * @param dto
     * @return
     */
    public boolean bindBdPush(UserBindDto dto){
        UserBdpushBind query = new UserBdpushBind();
        query.setUserId(dto.getUserId());
        List<UserBdpushBind> rs = bindDao.findByColumns(query);
        UserBdpushBind ub = null;
        if(rs.size()>0){
            ub = rs.get(0);

            ub.setUpdateDate(new Date());
            if(dto.getFlag()==0){
                ub.setIosChannelId(dto.getChannel_id());
                ub.setIosUserId(dto.getChannel_id());
            }
            if(dto.getFlag()==1){
                ub.setAndroidChannelId(dto.getChannel_id());
                ub.setAndroidUserId(dto.getChannel_id());
            }

            bindDao.update(ub);
        }else{
            ub = new UserBdpushBind();
            if(dto.getFlag()==0){
                ub.setIosChannelId(dto.getChannel_id());
                ub.setIosUserId(dto.getChannel_id());
            }
            if(dto.getFlag()==1){
                ub.setAndroidChannelId(dto.getChannel_id());
                ub.setAndroidUserId(dto.getChannel_id());
            }
            ub.setUserId(dto.getUserId());
            ub.setAddDate(new Date());
            bindDao.insert(ub);
        }
        return true;
    }

    /**
     * 后台登陆
     * @param userName
     * @param pwd
     * @return
     */
//    public boolean loginSys(String userName,String pwd){
//        boolean flag = false;
//        SysUser su = new SysUser();
//        su.setUserName(userName);
//        su.setUserPwd(Encrypt.generatePassword(pwd));
//        List<SysUser> list = sysUserDao.findByColumns(su);
//        if(list.size()>0) {
//            flag = true;
//        }
//        return flag;
//    }



	public Pager findAllUsersByDay(String day, Integer page, Integer rows) {
		Pager pager = userDao.querPageListByDay(day,page,rows);
		return pager;
	}
	
	public void saveUserFriend(UserFriend userFriend) {
	    userFriendDao.insert(userFriend);
	}
	
	public List<UserFriend> findUserFriends(UserFriend userFriend) {
	    return userFriendDao.findByColumns(userFriend);
	}
	
	public List<User> findFriends(int userId, int type) {
	    return userFriendDao.findFriends(userId, type);
	}
	
	public void saveUserListeningRecording(UserListeningRecording entity) {
	    userListeningRecordingDao.insert(entity);
	}
	
	public void updateUserListeningRecording(UserListeningRecording entity) {
	    userListeningRecordingDao.update(entity);
	}
	
	public UserListeningRecording findUserListeningRecording(int userId, int type, String date) {
	    UserListeningRecording entity = new UserListeningRecording();
	    entity.setDate(date);
	    entity.setUserId(userId);
	    entity.setType(type);
	    List<UserListeningRecording> records = userListeningRecordingDao.findByColumns(entity);
	    return records.size() > 0 ? records.get(0) : null;
	}
	
	public List<UserListeningRecording> get7DaysRecords(int userId) {
	    return userListeningRecordingDao.get7DaysRecords(userId, TPOUtils.get7DaysAgo());
	}
	
	public int getUserListeningRecordingTotalCount(int userId, int type) {
	    return userListeningRecordingDao.getUserListeningRecordingTotalCount(userId, type);
	}

	public boolean loginSysNew(String userName, String userPwd) {
		 boolean flag = false;
	        TUser su = new TUser();
	        su.setUsername(userName);
	        su.setPassword(Encrypt.generatePassword(userPwd));
	        List<TUser> list = tUserDao.findByColumns(su);
	        if(list.size()>0) {
	            flag = true;
	        }
	        return flag;
	}
	
	public TeacherVo findTeacherById(int teacherId) {
	    return userDao.findTeacherById(teacherId);
	}

}
